<template>
  <!-- 送装服务明细表 -->
  <div class="serviceQualityReportForm">
    <ContentWrap>
      <FormContainer :column="4">
        <el-form ref="form" :model="formData" :rules="formRules" label-width="80px">
          <el-form-item prop="officeId" label="办事处">
            <SearchSelectPicker
              url="/call-center/api/v1/mscInfo/office/ref/page"
              placeholder="请选择办事处"
              lable-name="name"
              value-name="code"
              method="get"
              :value.sync="formData.officeId"
              @selectChange="officeChange"
            ></SearchSelectPicker>
            <!-- <OfficeOrDealerSelect v-model="formData.officeId" :obj="{value:'officeId',name:'officeName'}" :api-func="pageOrderDetailOffice" :time="formData.times" :disabled="disabled" placeholder="请选择办事处" filterable clearable></OfficeOrDealerSelect> -->
          </el-form-item>
          <el-form-item prop="dealerId" label="经销商名称">
            <!-- <OfficeOrDealerSelect v-model="formData.dealerId" :emit="formData.officeId" :obj="{value:'dealerId',name:'dealerName'}" :api-func="pageOrderDetailDealer" :others-raw="{officeId: formData.officeId}" :time="formData.times" :disabled="dealerDisabled" placeholder="请选择经销商" filterable clearable></OfficeOrDealerSelect> -->
            <SearchSelectPicker
              url="/call-center/api/v1/mscInfo/dealer/ref/page"
              method="get"
              placeholder="请选择经销商"
              :params="{query:{officeCode:formData.officeId},type:0}"
              lable-name="name"
              value-name="code"
              custom-name="codeOrName"
              :parent-id="formData.officeId"
              :value.sync="formData.dealerId"
              :disabled="!formData.officeId"
              clearable
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="times" :span="7" label="日期">
            <el-date-picker
              v-model="formData.times"
              type="daterange"
              value-format="yyyy-MM-dd"
              opt
              operator=">"
              :limite="new Date()"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <el-form-item prop="deliveryType" label="订单类型">
            <el-select v-model="formData.deliveryType" filterable clearable multiple placeholder="请选择订单类型">
              <el-option v-for="(item, index) of deliveryTypeList" :key="index" :value="item.dictCode" :label="item.dictName" />
            </el-select>
          </el-form-item>
          <el-form-item :span="5">
            <Button @click="$refs.form.resetFields()">重置</Button>
            <Button type="primary" enter @click="queryHandle">查询</Button>
          </el-form-item>
        </el-form>
      </FormContainer>
      <div class="button-container" style="padding-top:0">
        <ExportPane :table-config="tableConfig" :other-raw="otherRaw" :data-source="selectedAry" :query-data-fun="queryHandle" filename="送装服务明细报表">导出</ExportPane>
      </div>
      <table-box
        ref="table"
        no-request
        :table-config="tableConfig"
        :other-filters="otherFilters"
        :other-raw="otherRaw"
        @selection-change="selectionChange"
      >
        <el-table-column slot="before" type="selection" width="55"></el-table-column>
        <el-table-column slot="before" type="index" label="序号" width="55"></el-table-column>
      </table-box>
    </ContentWrap>
  </div>
</template>
<script>
import ContentWrap from '@/components/ContentWrap'
import SearchSelectPicker from '@/components/SearchSelectPicker'
import FormContainer from '@/components/FormContainer'
import Button from '@/components/Button'
import ExportPane from '@/components/ExportPane'
import { pageOrderDetailOffice, pageOrderDetailDealer } from '@/api/serviceQuality'
// import OfficeOrDealerSelect from '../components/officeOrDealerSelect'
import { filtersRaw, checkRange } from '@/utils'
import { ccDict } from '@/api/dataDict'

export default {
  name: 'ServiceQualityReportForm',
  components: {
    ContentWrap,
    FormContainer,
    Button,
    ExportPane,
    // OfficeOrDealerSelect,
    SearchSelectPicker
  },
  data() {
    const validatorTimes = (r, v, c) => {
      if (v instanceof Array && v.length === 2) {
        // 不超过三个月
        if (checkRange()(v)) {
          c()
        } else {
          c(new Error('日期跨度不能大于三个月'))
        }
      } else {
        c(new Error('请选择日期'))
      }
    }
    return {
      pageOrderDetailOffice,
      pageOrderDetailDealer,
      otherFilters: [],
      otherRaw: {},
      formData: {
        times: [],
        officeId: '',
        dealerId: '',
        deliveryType: ''
      },
      formRules: {
        times: [{ required: true, type: 'array', message: '请选择日期', trigger: 'change' },
          { validator: validatorTimes, trigger: 'change' }]
      },
      tableConfig: {
        interfacePath: '/call-center/api/v1/reportServiceDetail/page',
        pageFlag: true,
        hideFuncBar: true,
        // 表格字段动态配置
        setting: [
          {
            prop: 'officeId',
            label: '办事处编码',
            width: 110
          },
          {
            prop: 'officeName',
            label: '办事处',
            minWidth: 100
          },
          {
            prop: 'dealerId',
            label: '经销商编码',
            width: 110
          },
          {
            prop: 'dealerName',
            label: '经销商名称',
            minWidth: 110
          },
          {
            prop: 'businessStatus',
            label: '经销商经营状态',
            minWidth: 140,
            propEnum: {
              appCode: 'call-center',
              domainCode: 'marketing',
              dictTypeCode: 'BUSINESS_STATUS'
            }
          },
          {
            prop: 'scheduleCount',
            label: '已排工单量',
            minWidth: 110
          },
          {
            prop: 'deliveryCount',
            label: '送货完成量',
            minWidth: 110
          },
          {
            prop: 'completionCount',
            label: '安装完成量',
            minWidth: 110
          },
          {
            prop: 'appraiseCount',
            label: '评价完成量',
            minWidth: 110
          },
          // 报表新增字段‘好评单量’、‘好评单量占比’、‘差评单量’、‘差评单量占比’；（送装服务明细表
          {
            prop: 'greater',
            label: '好评单量',
            minWidth: 110,
            formatData: v => {
              const { greater } = v
              if (!/^\d+$/.test(greater)) return '-'
              return greater
            }
          },
          {
            prop: '',
            label: '好评单量占比',
            minWidth: 120,
            formatData: v => {
              const { greater, less } = v
              if (!/^\d+$/.test(greater) || !/^\d+$/.test(less)) return '-'
              if (greater + less === 0) return 0
              return `${((greater / (greater + less)) * 100).toFixed(2)}%`
            }
          },
          {
            prop: 'less',
            label: '差评单量',
            minWidth: 110,
            formatData: v => {
              const { less } = v
              if (!/^\d+$/.test(less)) return '-'
              return less
            }
          },
          {
            prop: '',
            label: '差评单量占比',
            minWidth: 120,
            formatData: v => {
              const { greater, less } = v
              if (!/^\d+$/.test(greater) || !/^\d+$/.test(less)) return '-'
              if (greater + less === 0) return 0
              return `${((less / (greater + less)) * 100).toFixed(2)}%`
            }
          }, {
            prop: 'deliveryType',
            width: 120,
            label: '订单类型',
            propEnum: {
              appCode: 'call-center',
              domainCode: 'marketing',
              dictTypeCode: 'CC_ORDER_TYPE'
            }
          }, {
            prop: 'serviceAttitude',
            label: '服务态度',
            minWidth: 100,
            formatData: v => {
              return ((v.serviceAttitude || 0) / 2).toFixed(2)
            }
          },
          {
            prop: 'deliverySpeed',
            label: '送货速度',
            minWidth: 100,
            formatData: v => {
              return ((v.deliverySpeed || 0) / 2).toFixed(2)
            }
          },
          {
            prop: 'installationQuality',
            label: '安装质量',
            minWidth: 100,
            formatData: v => {
              return ((v.installationQuality || 0) / 2).toFixed(2)
            }
          },
          {
            prop: 'satisfaction',
            label: '综合满意度',
            minWidth: 110,
            formatData: v => {
              return ((v.satisfaction || 0) / 2).toFixed(2)
            }
          },
          {
            prop: 'grade',
            label: '等级',
            minWidth: 80
          }
        ]
      },
      selectedAry: [],
      deliveryTypeList: [] // 订单类型列表
    }
  },
  computed: {
    disabled() {
      return !(this.formData.times instanceof Array) || this.formData.times.length !== 2 || !checkRange()(this.formData.times)
    },
    dealerDisabled() {
      return this.disabled || !this.formData.officeId
    }
  },
  created() {
    this.getDeliveryTypeList()
    if (!this.$isCC) {
      // 办事处必选
      this.$set(this.formRules, 'officeId', [{ required: true, message: '请选择办事处', trigger: 'change' }])
      this.pageOrderDetailOffice = (...args) => {
        return pageOrderDetailOffice.call(this, ...args, false).then(res => {
          return res.filter(e => this.$store.getters.otherCode.includes(e.officeId))
        })
      }
    }
  },
  methods: {
    // 获取订单类型字典
    getDeliveryTypeList() {
      ccDict('CC_ORDER_TYPE').then(res => {
        this.deliveryTypeList = res.data
      })
    },
    // 查询
    queryHandle(type) {
      return this.$refs.form.validate().then(() => {
        const list = []
        const otherRaw = {}
        const eq = ['officeId', 'dealerId']
        for (const [k, v] of Object.entries(this.formData)) {
          if (v === undefined || v === null || v === '' || (v instanceof Array && v.length <= 0)) {
            continue
          }
          if (k === 'times') {
            otherRaw.startDate = v[0]
            otherRaw.endDate = v[1]
          } else if (k === 'deliveryType') {
            list.push(filtersRaw(k, `[${v.join(',')}]`, 'in'))
          } else if (eq.includes(k)) {
            // otherRaw[k] = v
            list.push(filtersRaw(k, v, '='))
          } else {
            list.push(filtersRaw(k, v, 'like'))
          }
        }
        this.otherRaw = otherRaw
        this.otherFilters = list
        if (type !== 'export') {
          this.refreshTable()
        }
        return list
      })
    },
    // 刷新表格
    refreshTable(type) {
      this.$nextTick(() => {
        this.$refs.table.initTableData(type)
      })
    },
    // 表格选中事件
    selectionChange(val) {
      this.selectedAry = val
    },
    officeChange(v) {
      v = v || {}
      this.$set(this.formData, 'dealerId', '')
    }
  }
}
</script>
<style lang='scss' module>
</style>
